﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace editor.cfg
{
    public class Field
    {
        // public int Id { get; private set; }
        public Bean Host { get; private set; }
        public string Name { get; private set; }
        public string Desc { get; private set; }
        public string Tips { get; private set; }

        public int ShowOrder { get; private set; }

        public TType FType { get; private set; }

        private string _stype;
        private readonly Dictionary<string, string> _attrs = new Dictionary<string, string>();

        public string Sep { get; private set; }

        public Field(Bean host, XmlElement ele)
        {
            Host = host;
            Name = ele.GetAttribute("name");

            _stype = ele.GetAttribute("type");
            if (string.IsNullOrEmpty(_stype))
                Err($"type missing");

            var desc = ele.GetAttribute("desc");
            Desc = (string.IsNullOrWhiteSpace(desc) ? Name : desc).Replace('_', ' ');

            Tips = ele.GetAttribute("tip");
            ShowOrder = int.TryParse(ele.GetAttribute("show_order"), out var x) ? x : 0;
            //if (int.TryParse(ele.GetAttribute("id"), out var id))
            //{
            //    Id = id;
            //}

            AddAttr(ele, "sep", "ref", "path");
        }

        private void AddAttr(XmlElement e, params string[] attrNames)
        {
            foreach (string attrName in attrNames)
                _attrs.Add(attrName, e.GetAttribute(attrName));
        }

        public override string ToString()
        {
            return Name;
        }

        public void Resolve()
        {
            FType = TType.Create(Host.Defines, Host.Namespace, _stype.Split(',', ':'), _attrs);

            var d = _attrs["sep"];
            if (string.IsNullOrEmpty(d) && FType is TBean)
            {
                d = (FType as TBean).BeanType.Delimiter;
            }
            Sep = d;

            if (string.IsNullOrWhiteSpace(Tips))
            {
                Tips = FType.Desc;
            }
        }

        private void Err(string msg)
        {
            throw new Exception($"bean:{Host.FullName}.field:{Name} {msg}");
        }
    }
}
